'''
Author: Mr.Sen
LastEditTime: 2021-02-20 23:39:18
Description: 用来处理上传数据
Website: https://grimoire.cn
Copyright (c) Mr.Sen All rights reserved.
'''
import time
import html
import re
import markdown
from database.models import *
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required

# from django.views.decorators.csrf import csrf_exempt,csrf_protect


def JsonResponseOk(dic={}):
    okDic = {
        "msg": "",
        "status": 1
    }
    okDic.update(dic)
    return JsonResponse(okDic)


def JsonResponseFail(dic={}):
    okDic = {
        "msg": "",
        "status": 0
    }
    # dic.update(okDic)
    okDic.update(dic)
    return JsonResponse(okDic)


'''
    url = upload/meta/
    私有
    创建新的分组
    参数：name:string
'''


@login_required(login_url='/login/')
def uploadMeta(request):  # 创建分组
    metaName = html.escape(request.POST.get("name"))
    if metaName is None:
        return JsonResponseFail({"msg": "name 参数不能为空"})
    else:
        # user = users.objects.filter(id=int(request.user.id)).first()
        user = users.objects.get(id=request.user.id)
        meta.objects.create(name=metaName, count=0, user=user)
        return JsonResponseOk({"msg": "分组："+metaName+" 创建成功"})


'''
    url = "upload/article/"
    这个函数是用来处理上传的文章的
    首先要判断是否拥有文章的修改权限
    主要是要解决是否有重复文章
    如果有，就修改重复文章
    如果没有，就添加文章
'''


@login_required(login_url='/login/')
def uploadArticle(request):  # 新建文章

    contentId = html.escape(request.POST.get("contentId"))
    content = html.escape(request.POST.get("content"))  # raw markdown
    metas = html.escape(request.POST.get("meta"))  # 分组
    # title = request.POST.get("title")  # 文章标题
    title = content.split('\n', 1)[0].replace("#", "").strip()
    content = content[content.find("\n")+2::]
    # slug = request.POST.get("slug", title)  # 文章缩略名
    isPublic = html.escape(request.POST.get("isPublic", "private"))

    if (content is None) or (metas is None) or (title is None) or (len(isPublic) < 3):
        # print(content, metas, title)
        return JsonResponseFail({"msg": "必填项不能为空"})
    else:
        newMeta = meta.objects.filter(id=int(metas)).first()
        if newMeta is None:
            return JsonResponseFail({"msg": "暂无此分类"})

        if newMeta.user_id != request.user.id:
            return JsonResponseFail({"msg": "暂无此分类"})

        repeat = contents.objects.filter(id=int(contentId)).first()
        if (repeat is not None) and (repeat.authorId != request.user.id):  # 未拥有编辑权限
            return JsonResponseFail({"msg": "未找到该文章"})

        extension = [
            "markdown.extensions.fenced_code",
            "markdown.extensions.tables",
            "markdown.extensions.sane_lists",
        ]
        contentHtml = markdown.markdown(content, extensions=extension)
        newMeta.lastEdit = int(time.time())  # 更新时间戳

        if repeat is not None and repeat.authorId == request.user.id:  # 允许编辑
            if repeat.meta_id != newMeta.id:
                oldMeta = meta.objects.filter(id=repeat.meta_id).first()
                oldMeta.count = oldMeta.count - 1
                oldMeta.save()
                newMeta.count = newMeta.count + 1
                newMeta.save()

            repeat.title = title
            # repeat.slug = slug
            repeat.text = contentHtml
            repeat.rawtext = content
            repeat.meta = newMeta
            # repeat.created = int(time.time())
            repeat.isPublic = isPublic
            repeat.save()
            return JsonResponseOk({"msg": "文章覆盖完毕"})

        if repeat is None:
            newMeta.count = newMeta.count + 1
            newMeta.lastEdit = int(time.time())
            newMeta.save()
            user = contents.objects.create(title=title, text=contentHtml, rawtext=content,
                                           authorId=request.user.id, meta=newMeta, created=int(time.time()), isPublic=isPublic)
            return JsonResponseOk({"msg": "文章保存完毕", "redirect": user.id})


'''
    url = "/deleteArticle/?delete="
    用来删除文章
'''


@login_required(login_url="/login/")
def deleteArticle(request):
    deleteTarget = html.escape(request.GET.get("delete"))
    if not deleteTarget.isdigit():
        return JsonResponseFail({"msg": "参数错误"})

    content = contents.objects.filter(id=int(deleteTarget)).first()

    if content is None:
        return JsonResponseFail({"msg": "文章未找到"})

    if content.authorId != request.user.id:
        return JsonResponseFail({"msg": "这是你的么就乱动???"})

    content.meta.count = content.meta.count - 1
    content.meta.save()
    content.delete()
    return JsonResponseOk({"msg": "删除成功"})


'''
    url = "/deleteMeta/?meta="
    用来删除分组
'''


@login_required(login_url="/login/")
def deleteMeta(request):

    deleteTarget = html.escape(request.GET.get("delete"))
    if deleteTarget is None:
        return JsonResponseFail({"msg": "参数错误"})

    if not deleteTarget.isdigit():
        return JsonResponseFail({"msg": "参数错误"})

    metas = meta.objects.filter(id=int(deleteTarget)).first()
    if metas is None:
        return JsonResponseFail({"msg": "分类未找到"})

    if metas.user.id != request.user.id:
        return JsonResponseFail({"msg": "这是你的么就乱动???皮痒了??"})

    metas.delete()
    return JsonResponseOk({"msg": "删除成功"})


'''
    url = "renameMeta/"
    重命名分组
'''


@login_required(login_url="/login/")
def renameMeta(request):

    metaName = html.escape(request.POST.get("name"))
    metaId = html.escape(request.POST.get("metaId"))
    if metaName is None or metaId is None or not metaId.isdigit():
        return JsonResponseFail({"msg": "name 参数不能为空"})
    else:
        # user = users.objects.get(id=int(request.user.id))
        # res = meta.objects.create(name=metaName, count=0, user=user)
        metaInfo = meta.objects.filter(id=int(metaId)).first()
        if metaInfo.user.id != request.user.id:
            return JsonResponseFail({"msg": "吔屎了你！"})
        metaInfo.name = metaName
        metaInfo.save()
        return JsonResponseOk({"msg": "分组："+metaName+" 更名成功"})


'''
    url = "/updateUserInfo/"
    这个接口是用来更新设置信息的
'''


@login_required(login_url="/login/")
def updateUserInfo(request):

    user = users.objects.get(id=request.user.id)
    postObject = request.POST

    # print("Hello world", postObject.get("iconfont"),postObject.get("nickname"),postObject.get("avatar"))

    nickname = html.escape(postObject.get("nickname"))
    avatar = postObject.get("avatar")
    icons = html.escape(postObject.get("iconListString"))
    iconfont = postObject.get("iconfont")

    regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'

    if not iconfont.startswith("//at.alicdn.com"): return JsonResponseFail({"msg":"只能使用iconfont哦"})

    if not (nickname == "" or nickname is None):
        user.nicName = nickname
    if not (avatar == "" or avatar is None):
        user.avatar = avatar
    if not (icons == "" or icons is None):
        user.icons = icons
    if not (iconfont == "" or iconfont is None):
        user.iconfont = iconfont

    user.save()
    return JsonResponse({"status": 1, "msg": "信息更新成功"})

# from rich import print
# @csrf_exempt
# def testApi(requests):
#     print(dict(requests.POST))
#     return JsonResponse(dict(requests.POST))
